//
//  AppDelegate.m
//  XMLY
//
//  Created by 曾杰 on 15/11/4.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "AppDelegate.h"
#import "PKRootLeftViewController.h"
#import "UserGuideViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PKPlayerManger.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ChildListModel.h"
@interface AppDelegate ()
@property (nonatomic, strong)UserGuideViewController *userGuideVC;
@property (nonatomic, strong)PKRootLeftViewController *rootLeftVC;
@property (nonatomic, strong)UINavigationController * naVC;
@property (nonatomic, strong)PKPlayerManger *player;
@property (nonatomic, strong)NSTimer * timer;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    _userGuideVC = [[UserGuideViewController alloc] init];
    _rootLeftVC = [[PKRootLeftViewController alloc] init];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"第一次启动");
        //如果是第一次启动的话,使用UserGuideViewController (用户引导页面) 作为根视图
        
        _naVC = [[UINavigationController alloc]initWithRootViewController:_userGuideVC];
    
        _userGuideVC.rootLeftVC = self.rootLeftVC;
        self.window.rootViewController = _naVC;
        
    }
    else
    {
        NSLog(@"不是第一次启动");
        //如果不是第一次启动的话,创建根视图控制器
        
//        PKRootLeftViewController *rootLeftVC = [[PKRootLeftViewController alloc]init];
        self.window.rootViewController = _rootLeftVC;
        
    }
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    [self.window makeKeyAndVisible];
    return YES;
}

-(void)configNowPlayingInfoCenter{
    
    
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
       ChildListModel * model = [_player.musicArr objectAtIndex:_player.index];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        //歌曲名称
        if (model.title) {
            
            [dict setObject:model.title forKey:MPMediaItemPropertyTitle];
        }
        
        
        //演唱者
//        [dict setObject:[info objectForKey:@"singer"] forKey:MPMediaItemPropertyArtist];
//        
//        //专辑名
//        [dict setObject:[info objectForKey:@"album"] forKey:MPMediaItemPropertyAlbumTitle];
//        
//        //专辑缩略图
        UIImage *image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.coverLarge]]];
        if (image) {
            
            MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
            [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
        }
//
        //音乐剩余时长
        [dict setObject:[NSNumber numberWithDouble:self.player.finishTime-self.player.currentTime] forKey:MPMediaItemPropertyPlaybackDuration];
        
        //音乐当前播放时间 在计时器中修改
        [dict setObject:[NSNumber numberWithDouble:self.player.currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        
        //设置锁屏状态下屏幕显示播放音乐信息
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlPause:
            {
                 [self playSong];
            }
                break;
             
                case UIEventSubtypeRemoteControlPlay:
            {
                [self playSong];
            }
            break;
                case UIEventSubtypeRemoteControlNextTrack:
            {
            
                 [self playLastSong];
                
            }
                break;
                case UIEventSubtypeRemoteControlPreviousTrack:
            {
              
                  [self playNextSong];
            }
                break;
        }
        
        
          }
}


-(void)playSong
{

    [_player playAndPause];
    
}





-(void)playNextSong
{
      _player.index--;
    if (_player.index==-1) {
        _player.index = _player.musicArr.count-1;
    }
  
    [_player playWithIndex:_player.index];
    [self configNowPlayingInfoCenter];
}


-(void)playLastSong
{
    _player.index++;
    if (_player.index==_player.musicArr.count) {
        _player.index=0;
    }
     [_player playWithIndex:_player.index];
    [self configNowPlayingInfoCenter];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(configNowPlayingInfoCenter) userInfo:nil repeats:YES];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
   
    _player = [PKPlayerManger shareManger];

    
    
    [self configNowPlayingInfoCenter];

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
   
    [_timer invalidate];
    _timer = nil;
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"indexChange" object:nil userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%ld",self.player.index]  forKey:@"index"]];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
